const { Op } = require("sequelize");
const Stock = require("../model/Stock");
const Merchandise = require("../model/Merchandise");
const crypto = require("crypto");

exports.createStock = async function (userObj) {
  const ins = await Stock.create({
    userId: userObj.userId,
    merchandiseId: userObj.merchandiseId
  });
  console.log(ins, "创建商品库存");
};

exports.updateStock = async function (userObj) {
  
  const ins = await Stock.update(
    {
      quantity: +userObj.quantity
    },
    {
      where: {
        id: userObj.id,
        userId: userObj.uid,
        merchandiseId: userObj.merchandiseId,
      },
    }
  );
  if(!ins[0]) {
    throw '库存不存在'
  }
};

exports.getStockList = async function (uid, page = 1, limit = 10) {
  const where = {
    userId: uid,
    // merchandiseId: userObj.merchandiseId,
  }
  const res = await Stock.findAndCountAll({
    where,
    offset: (page - 1) * limit,
		limit: +limit,
    include: {
      model: Merchandise,
      as: 'merchandise',
      attributes: ['name', 'price', 'imgUrl'],
    },
  });
  if(!res) {
    throw '库存不存在'
  }
  // console.log(ins.toJSON(), "库存查询成功");
  return {
    total: res.count,
    data: JSON.parse(JSON.stringify(res.rows)),
  };
}

exports.getStockDetail = async function (userObj) {
  const ins = await Stock.findOne({
    where: {
      userId: userObj.uid,
      merchandiseId: userObj.merchandiseId,
    },
    include: {
      model: Merchandise,
      as: 'merchandise',
      attributes: ['name', 'price', 'imgUrl'],
    },
  });
  if(!ins) {
    throw '库存不存在'
  }
  console.log(ins.toJSON(), "库存查询成功");
  return ins.toJSON();
}